package com.instpower.things.instpower;

import com.instpower.things.transport.DataBuffer;
import com.instpower.things.transport.Request;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

import static com.instpower.things.helper.DataConverter.printHex;

/**
 * @ClassName InstpowerMessageDecoder
 * @Author: hellmash@gmail.com
 * @Date: 2020/2/23
 * @Version: 1.0.0
 * @Description: 解码
 */
public class InstpowerMessageDecoder extends ByteToMessageDecoder {

    private final Logger logger = LoggerFactory.getLogger("SYS");

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
        if(!buf.isReadable())
            return;
        try{
            logger.debug("进入编码:{}",buf.readableBytes());
            buf.retain();
            Request request = new Request(new DataBuffer(buf));
            out.add(request);
            buf.release();
        }catch (Exception e){
            logger.error("decode failed", e);
        }finally {
            if(buf.readerIndex() != buf.writerIndex()){
                logger.debug("buf.readerIndex() != buf.writerIndex()");
                buf.readerIndex(buf.writerIndex());
            }
        }
    }
}
